package com.juku2024.juku

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wanban.adutils.callback.OnLoadAdCallback
import com.wanban.adutils.tools.AdConstants
import com.wanban.adutils.utils.*
import com.juku2024.juku.adapter.NoteAdapter
import com.juku2024.juku.db.entity.NoteModel
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.dialog.CommonDialog
import com.juku2024.juku.dialog.DialogUtils
import com.juku2024.juku.tools.AlertUtils
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.RxUtils
import com.juku2024.juku.tools.SPUtil
import com.juku2024.juku.viewmodel.MainViewModel
import com.juku2024.juku.widget.LoadingView
import io.reactivex.disposables.Disposable

class NodeMainActivity : AppCompatActivity() {

    private lateinit var tvAdd: TextView
    private lateinit var tvSearch: TextView
    private lateinit var btnFeedback: View
    private lateinit var etSearch: EditText
    private lateinit var ivEmpty: ImageView
    private lateinit var recyclerView: RecyclerView
    private lateinit var loadingView: LoadingView
    private lateinit var headerLayout: View
    private lateinit var contentLayout: View
    private lateinit var layoutSearchEt: View
    private lateinit var adBannerRoot: ViewGroup
    private lateinit var btnExport: View
    // 返回双击
    private var exitDisposable: Disposable? = null
    private val noteAdapter by lazy { NoteAdapter(noteList) }
    private val noteList: ArrayList<NoteModel> by lazy { ArrayList() }
    private val viewModel by lazy { getViewModel(MainViewModel::class.java) }

    private var deleteDialog : CommonDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 根据设置来改编状态栏颜色
//        AppUtils.setAppStyle(this)
        // 处理按home键退出后，再次进入会重启App
        if (ignoreHomeLauncher()) return
        setContentView(R.layout.activity_node_main)
        initView()
        bindEvent()
        // 加载开屏广告
        if (OpenAdTools.isAdLoadSuccess()) {
            OpenAdTools.showAd(this)
        }
        if (!VideoInterstitialAdTools.isAdLoadSuccess()) {
            VideoInterstitialAdTools.loadAd(this)
        }
        // 注册ReopenAd
        ReopenAdTools.init(this)
        layoutSearchEt.visibility = View.VISIBLE
        tvSearch.visibility = View.VISIBLE
        doHttpMain()

        loadBanner()
    }

    private fun initView() {
        adBannerRoot = findViewById(R.id.ad_banner_Root)
        headerLayout = findViewById(R.id.node_header)
        contentLayout = findViewById(R.id.node_content)
        tvAdd = findViewById(R.id.tvAdd)
        btnFeedback = findViewById(R.id.btn_feedback)
        tvSearch = findViewById(R.id.tvSearch)
        etSearch = findViewById(R.id.etSearch)
        ivEmpty = findViewById(R.id.ivEmpty)
        recyclerView = findViewById(R.id.recyclerView)
        loadingView = findViewById(R.id.node_loadingView)
        layoutSearchEt = findViewById(R.id.layoutSearchEt)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.setHasFixedSize(true)
        recyclerView.adapter = noteAdapter
        btnExport = findViewById(R.id.iv_export)
    }

    private fun bindEvent() {
        tvAdd.setOnClickListener {
            loadingView.showLoading()
            val downloadAdTools = CommonAdTools()
            downloadAdTools.loadAd(this, AdConstants.AD_ID_DOWNLOAD_INTERSTITIAL, object: OnLoadAdCallback(){

                override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                    super.onAdLoaded(ad, *tag)
                    downloadAdTools.showAdInActivity(this@NodeMainActivity)
                }

                override fun onAdLoadFailed(errorCode: Int) {
                    super.onAdLoadFailed(errorCode)
                    loadingView.hideLoading()
                    val intent = Intent(this@NodeMainActivity, NoteDetailActivity::class.java)
                    startActivity(intent)
                }

                override fun onAdComplete() {
                    super.onAdComplete()
                    loadingView.hideLoading()
                    val intent = Intent(this@NodeMainActivity, NoteDetailActivity::class.java)
                    startActivity(intent)
                }
            })
        }

        tvSearch.setOnClickListener {
            excSearch()
        }

        btnFeedback.setOnClickListener {
            val intent = Intent(this, FeedbackActivity::class.java)
            startActivity(intent)
        }

        etSearch.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if (p0 == null || TextUtils.isEmpty(p0.toString())) {
                    noteAdapter.setList(noteList)
                    ivEmpty.visibility = if (noteAdapter.data.isEmpty()) {
                        View.VISIBLE
                    } else {
                        View.GONE
                    }
                }
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })

        etSearch.setOnEditorActionListener { _, i, _ ->
            excSearch()
            return@setOnEditorActionListener false
        }

        noteAdapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(this, NoteDetailActivity::class.java)
            intent.putExtra("id", noteAdapter.data[position].id)
            startActivity(intent)
        }

        noteAdapter.setOnItemLongClickListener { _, _, position ->
            if (deleteDialog == null) {
                deleteDialog = DialogUtils.showCommonDialog(
                    this@NodeMainActivity,
                    "您确定要删除当前记录吗？",
                    getString(R.string.confirm), {
                        deleteDialog?.dismiss()
                        NoteRoomUtils.getInstance().noteDao().delete(noteAdapter.data[position].id)
                        ivEmpty.visibility = if (noteAdapter.data.isEmpty()) {
                            View.VISIBLE
                        } else {
                            View.GONE
                        }
                        noteAdapter.removeAt(position)
                    },
                    getString(R.string.cancel), {
                        deleteDialog?.dismiss()
                    }
                )
            }
            deleteDialog?.show()
            return@setOnItemLongClickListener true
        }

        btnExport.setOnClickListener {
            val intent = Intent(this, NoteExportActivity::class.java)
            startActivity(intent)
        }
    }

    private fun doHttpMain(){
        loadingView.showLoading()
        viewModel.doHttpHome({_, _, _, _ ->
            if (isFinishing || isDestroyed) return@doHttpHome
            loadingView.hideLoading()
            headerLayout.visibility = View.VISIBLE
            contentLayout.visibility = View.VISIBLE
        }, {
            if (isFinishing || isDestroyed) return@doHttpHome
            loadingView.hideLoading()
            loadingView.showErrorStatus(it?:getString(R.string.error_no_network), getString(R.string.retry)) {
                loadingView.showLoading()
                loadingView.postDelayed({
                    doHttpMain()
                }, 500)
            }
        })
    }

    private fun excSearch() {
        val key = etSearch.text?.toString()
        if (key == null || TextUtils.isEmpty(key)) {
            AlertUtils.alert("输入内容不能为空！")
            return
        }

        loadingView.showLoading()
        viewModel.verifyApp(key) {
            if (isFinishing || isDestroyed) return@verifyApp
            loadingView.hideLoading()
            // 只有定位执行成功的才能继续解锁
//            if (it && SPUtil.instance.isLocationOverseas()) {
            if (it) {
                Toast.makeText(this, "解锁成功！", Toast.LENGTH_LONG).show()
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                AppUtils.closeKeyboard(etSearch)
                finish()
            } else {
                val searchResult = noteAdapter.data.filter { it.title?.contains(key, false) == true } as ArrayList
                if (searchResult.isEmpty()) {
                    AlertUtils.alert("未搜索到指定的内容！！")
                    return@verifyApp
                }
                noteAdapter.setNewInstance(searchResult)
                ivEmpty.visibility = if (noteAdapter.data.isEmpty()) {
                    View.VISIBLE
                } else {
                    View.GONE
                }
            }
        }

    }

    override fun onResume() {
        super.onResume()
        noteList.clear()
        noteAdapter.setList(noteList)
        val list = NoteRoomUtils.getInstance().noteDao().queryAll()
        if (list.isNullOrEmpty()) {
            ivEmpty.visibility = View.VISIBLE
            return
        }

        noteList.addAll(list)
        ivEmpty.visibility = View.GONE
    }
    private fun <T : ViewModel> getViewModel(modelClass: Class<T>): T {
        return ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        ).get(modelClass)
    }
    @Suppress("DEPRECATION")
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (exitDisposable == null || exitDisposable?.isDisposed == true) {
            AlertUtils.alert("再按一次退出程序")
            exitDisposable = RxUtils.delay(2500) {}
        } else {
            super.onBackPressed()
            if (exitDisposable != null) {
                exitDisposable?.dispose()
                exitDisposable = null
            }
        }
    }

    private fun loadBanner(){
        val bannerAdTools = CommonAdTools()
        bannerAdTools.loadAd(this, AdConstants.AD_ID_VIDEO_DETAIL_PAUSE, object: OnLoadAdCallback(){
            override fun onAdLoaded(ad: Any?, vararg tag: Int) {
                super.onAdLoaded(ad, *tag)
                if (isFinishing) return
                adBannerRoot.visibility = View.VISIBLE
                bannerAdTools.showAd(adBannerRoot)
            }

            override fun onAdLoadFailed(errorCode: Int) {
                super.onAdLoadFailed(errorCode)
                if (isFinishing) return
            }
        })
    }


    /**
     * 防止按home退出后，再次进入app的时候重新启动
     */
    private fun ignoreHomeLauncher(): Boolean {
        try {
            if (!isTaskRoot) {
                val action = intent.action
                if (action != null && intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN == action) {
                    finish()
                    return true
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return false
    }
}